<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
  <title>PowerGIS</title>
  <link rel="icon" type="image/png" sizes="16x16" href="../../icons/favicon-16x16.png">
  <script type="text/javascript" src="../../js/require.min.js"></script>
  <script type="text/javascript" src="../../js/jquery.2.1.4.min.js"></script>
  <script type="text/javascript" src="../../plugins/page/jquery.page.js"></script>
  <style>
    @import url('../../plugins/pgearth/Widgets/widgets.css');
    @import url('../../plugins/page/jQuery.page.css');
    @import url('../../plugins/loading/loading.css');
    @font-face {
      font-family: Material Icons Outlined;
      font-style: normal;
      font-weight: 400;
      src: url(../../fonts/gok-H7zzDkdnRel8-DQ6KAXJ69wP1tGnf4ZGhUcel5euIg.312bdf7e.woff2) format("woff2"), url(../../fonts/gok-H7zzDkdnRel8-DQ6KAXJ69wP1tGnf4ZGhUcY.42ced8c1.woff) format("woff")
    }

    .material-icons-outlined {
      font-family: Material Icons Outlined;
      font-weight: 400;
      font-style: normal;
      display: inline-block;
      line-height: 1;
      text-transform: none;
      letter-spacing: normal;
      word-wrap: normal;
      white-space: nowrap;
      direction: ltr;
      -webkit-font-smoothing: antialiased;
      text-rendering: optimizeLegibility;
      -moz-osx-font-smoothing: grayscale;
      -webkit-font-feature-settings: "liga";
      font-feature-settings: "liga"
    }
    html, body, #mapContainer {
      width: 100%; height: 100%; margin: 0; padding: 0; overflow: hidden;
    }
    #no-credit{
      display: none
    }
    .all-btn{
      z-index: 100;
      display: block;
      margin: 1px;
      padding: 0;
      color: #fff;
      font-size: 1.14em;
      font-weight: 500;
      text-decoration: none;
      text-align: center;
      height: 32px;
      width: 32px;
      line-height: .4em;
      background-color: #303336;
      border: none;
      border-radius: 4px;
    }
    .filter-btn{
      position: absolute;
      top: 5px;
      right: 124px;
    }
    .data-btn{
      position: absolute;
      top: 5px;
      right: 84px;
    }
    .data-div{
      text-align: center;
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100vw;
      height: 25vh;
      z-index: 100;
      background-color: #fff;
    }
    .filter-panel{
      position: absolute;
      top: 5px;
      z-index: 98;
      height: 32px;
      background-color: #303336;
    }
    .table-div{
      width: 100vw;
      overflow-x: auto;
    }
    table{
      width: 100%;
      border-spacing: 0;
      /*表格设置合并边框模型*/
      border-collapse: collapse;
      text-align: center;
      color: #444;
    }
    table>tbody{
      height: 14.2vh;
      display: block;
      overflow-y: auto;
      overflow-x: auto;
      font-size: 14px;
    }
    table thead{
      font-size: 16px;
      background-color: #EFEEEF;
    }
    tbody tr:nth-child(even){
      background-color: #f8f9f9;
    }
    table thead,
    tbody tr {
      display: table;
      width: 99vw;
      table-layout: fixed;
      height: 25px;
    }
    /*关键设置：滚动条默认宽度是16px 将thead的宽度减16px*/
    table thead {
      width: calc( 100vw - 1em)
    }
    tbody tr:hover{
      background-color: #D1E9F9;
      cursor: pointer;
    }
    table td,
    table th{
      width: 100px;
      word-wrap: break-word;
    }
    .hide{
      display: none;
    }
    .tr-active {
      background-color: #D1E9F9 !important;
    }
    .active{
      color: #fff;
      fill: #fff;
      background: #48b;
      border-color: #aef;
      box-shadow: 0 0 5px #fff;
    }
    .data-title{
      font-weight: bold;
      width: 100%;
      height: 30px;
      line-height: 30px;
      background-color: #303336;
      color: #fff;
      text-align: left;
      padding-left: 20px;
    }
    ::-webkit-scrollbar {/*滚动条整体样式*/
      width: 10px;     /*高宽分别对应横竖滚动条的尺寸*/
      height: 8px;
    }
    ::-webkit-scrollbar-thumb {/*滚动条里面小方块*/
      border-radius: 5px;
      -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
      background: #676968;
    }
    ::-webkit-scrollbar-track {/*滚动条里面轨道*/
      -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
      border-radius: 5px;
      background: transparent;
    }
    .fl {
      float: left;
      display: inline;
    }
    .pr {
      position: relative;
    }
    .fr {
      float: right;
      display: inline;
    }
    #onlineGlobalSearchBtn {
      width: 32px;
      height: 32px;
      line-height: 0;
      font-size: 16px;
      border-radius: 0;
      border: 1px solid #d6d6d6;
      color: #7e7e7e;
      background: #fff;
    }
    #onlineGlobalSearchBtn:hover{
      cursor: pointer;
    }
    #globalSearchIpt {
      float: none;
      height: 30px;
      font-size: 13px;
      line-height: 1.0;
      color: #242424;
      background-color: #f2f2f2;
      vertical-align: middle;
      border-radius: 0;
      z-index: 0;
      border: 0;
      width: 260px;
    }
    .sel{
      height: 32px;
      margin-right: 5px;
    }
    @keyframes mymove {
      from {right:-400px;}
      to {right:166px;}
    }

    @-webkit-keyframes mymove {
      from {right:-400px;}
      to {right:166px;}
    }
    .move{
      animation:mymove 5s;
    }

    @keyframes myBackMove {
      from {right:166px;}
      to {right:-400px;}
    }

    @-webkit-keyframes myBackMove {
      from {right:166px;}
      to {right:-400px;}
    }
    .backmove{
      animation:myBackMove 4s;
    }
    .no-data{
      position: absolute;
      top: 110px;
      left: 49vw;
    }
  </style>
</head>
<body>
<div id="mapContainer">
  <div id="no-credit"></div>
  <div th:style="${detailsData.serviceType==4?'':'display: none'}">
    <!-- <button class="all-btn filter-btn" title="数据查询" onclick="showFilter(this)">-->
      <!-- <i aria-hidden="true" class="material-icons-outlined q-icon">filter</i>-->
     <!--</button>-->
    <button class="all-btn data-btn" title="图层数据" onclick="showDatas(this)">
      <i aria-hidden="true" class="material-icons-outlined q-icon">table_chart</i>
    </button>
  </div>
  <div class="filter-panel" id="filterPanel" style="right: -400px;">
    <select class="sel">
      <option>CQL</option>
    </select>
    <div id="searchPanel" class="fr">
      <div id="globalSearchDiv" class="form-group fl pr" style="border-color: rgb(178, 178, 178);">
        <input id="globalSearchIpt" type="text" class="form-control ip-input-txt online-input">
      </div>
      <span class="input-group-btn fl">
        <button id="onlineGlobalSearchBtn" type="button" style="border-left: none; color: rgb(0, 131, 203);">
          <i class="material-icons-outlined q-icon">search</i>
        </button>
      </span>
    </div>
  </div>
  <div class="data-div" id="data" th:if="${detailsData.serviceType==4}" style="display: none">
    <div class="load-container load1" id="loadEffect"><div class="loader">Loading...</div></div>
    <div class="data-title" >
      <span th:text="${detailsData.name}"></span>
      <span>( 要素：<span id="dataSize">0</span> )</span>
    </div>
    <div class="table-div">
      <table id="dataTable">
        <thead>
        <tr>
          <th th:each="attribute : ${baseData.attributes.attribute}"><span th:text="${attribute.name}"></span></th>
        </tr>
        </thead>
        <tbody>
          <!--<tr th:onclick="'javascript:showMapShape(\'MULTIPOLYGON\',\''+${infoStat.index}+'\');'" th:each="info,infoStat : ${shpInfo}" >-->
            <!--<td th:each="attribute : ${baseData.attributes.attribute}"><span th:text="${info[attribute.name]}"></span></td>-->
          <!--</tr>-->
        </tbody>

      </table>
    </div>
    <div class="table-footer tablePage">
      <select name="page_num">
        <option value="10" selected>10条/每页</option>
        <option value="20">20条/每页</option>
        <option value="30">30条/每页</option>
        <option value="40">40条/每页</option>
      </select>
    </div>
  </div>
</div>
<script type="text/javascript" th:inline="javascript">
  var layerType = [[${detailsData.serviceType}]]
  var changeType = [[${detailsData.changeType}]]
  // var unitName = [[${detailsData.aliasName}]]
  let originProj4js = [[${proj4js}]] // 原始坐标系对应的参数
  var proj4Code = [[${detailsData.proj4js}]]
  var epsg = [[${detailsData.aliasName}]] // 1：代表地理坐标系，2：代表投影坐标系
  var lastIndex // 记录上一次选中的第几行
  var tableDatas = []
  var columnsData
  const layerIp = '../../../' //'http://192.168.9.12:8085/'
  const layer3DIp = '../../../' //'http://192.168.9.12:8085/'
  const layerName = [[${detailsData.name}]] // 服务名称
  const serviceUrl = [[${detailsData.serviceUrl}]] // 服务地址
  var baseData = [[${baseData}]]
  require.config({
    baseUrl: "../../plugins/pgearth/", //"http://192.168.9.12:8099/layer/plugins/pgearth/", //"http://192.168.10.184:5000/statics/layer/plugins/pgearth",
    waitSeconds: 0
  });
  require([
    "Widgets/Viewer/Viewer",
    "Scene/WebMapServiceImageryProvider",
    "Scene/PGEarth3DTileset",
    "Core/GeometryInstance",
    "Core/GroundPolylineGeometry",
    "Core/Cartesian3",
    "Core/Rectangle",
    "Core/Color",
    "Core/ColorGeometryInstanceAttribute",
    "Scene/Camera",
    "Scene/GroundPolylinePrimitive",
    "Scene/PolylineMaterialAppearance",
    "Scene/Material",
    "Core/PGEarthTerrainProvider",
    "extends/widgets/loading/loading",
    "extends/layers/PldMeshLayer",
    "extends/layers/ElevationLayer",
    "Core/WebMercatorTilingScheme",
    "Core/GeographicTilingScheme",
    "ThirdParty/proj4",
      "Core/createGuid",
      "Scene/WebMapTileServiceImageryProvider",
      "Scene/GridImageryProvider",
      "Scene/createTileMapServiceImageryProvider",
  ], function(
    Viewer,
    WebMapServiceImageryProvider,
    PGEarth3DTileset,
    GeometryInstance,
    GroundPolylineGeometry,
    Cartesian3,
    Rectangle,
    Color,
    ColorGeometryInstanceAttribute,
    Camera,
    GroundPolylinePrimitive,
    PolylineMaterialAppearance,
    Material,
    PGEarthTerrainProvider,
    Loading,
    PldMeshLayer,
    ElevationLayer,
    WebMercatorTilingScheme,
    GeographicTilingScheme,
    proj4,
    createGuid,
    WebMapTileServiceImageryProvider,
    GridImageryProvider,
    createTileMapServiceImageryProvider
  ) {
    let allPrimitiveLayers = []
    viewer = new Viewer('mapContainer', {
      creditContainer: 'no-credit',
      animation: false,
      baseLayerPicker: true,
      geocoder: false,
      timeline: false,
      fullscreenButton: false,
      navigationHelpButton: false,
      sceneModePicker: false,
      imageryProvider: new GridImageryProvider({
        cells:14,
        glowColor: Color.WHITE,
        glowWidth:0.5,
        color: Color.fromCssColorString("#fffbf4"),
        backgroundColor: Color.fromCssColorString("#e5dfd3")
      })
    })
    if(navigator.onLine){
      viewer.imageryLayers.addImageryProvider(new WebMapTileServiceImageryProvider({
        url: "http://t0.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=1d109683f4d84198e37a38c442d68311",
        layer: "tdtBasicLayer",
        style: "default",
        format: "image/jpeg",
        tileMatrixSetID: "GoogleMapsCompatible",
        maximumLevel: 18
      }));
    }
    //设置初始位置
    viewer.camera.setView({
      destination: Cartesian3.fromDegrees(109, 33, 10000000), //10000000.0
    })
    //设置home键位置
    Camera.DEFAULT_VIEW_RECTANGLE = Rectangle.fromDegrees(100, 36, 120, 25);

    viewer._pgEarthWidget._creditContainer.style.display='none'
    var loading = new Loading()
    if (layerType === 1 || layerType === 4) {
      var layer = new WebMapServiceImageryProvider({
        url: layerIp + serviceUrl,
        tilingScheme: epsg === '1' ? new GeographicTilingScheme() : new WebMercatorTilingScheme()
      });
      test = viewer.imageryLayers.addImageryProvider(layer);
      // 获取坐标系
      let center = baseData ? baseData.nativeBoundingBox : {}
      if(originProj4js && originProj4js.crs_type === '2' && center.maxx){
        let minCenter = proj4(originProj4js.proj4js, '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs',[center.minx ? center.minx : 0, center.miny?center.miny:0]) // 源坐标系，目标坐标系，需要转换的值
        let maxCenter = proj4(originProj4js.proj4js, '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs',[center.maxx ? center.maxx : 0, center.maxy?center.maxy:0]) // 源坐标系，目标坐标系，需要转换的值
        if (minCenter.toString() === maxCenter.toString()) {
          return
        }
        viewer.camera.flyTo({
          destination : Rectangle.fromDegrees(minCenter[0], minCenter[1], maxCenter[0], maxCenter[1])
        });
      } else if (epsg === '1' && center.maxx){
        viewer.camera.flyTo({
          destination : Rectangle.fromDegrees(center.minx, center.miny, center.maxx, center.maxy)
        });
      }
    } else if (layerType === 2 || (layerType === 3 && changeType === 'terrain')) {
      var provider = new PGEarthTerrainProvider({
        url: layerIp + serviceUrl
      });

      viewer.terrainProvider = provider
    } else if (layerType === 3 && changeType === 'tif') {
      var layer = new ElevationLayer({
        url: layerIp + serviceUrl
      })
      viewer.scene.terrainProvider = layer;
    } else if (layerType === 7) {
      var entity = viewer.entities.add({
        position : Cartesian3.fromDegrees(109, 33, 2),
        model : {
          uri : layerIp + serviceUrl+'&uuid='+ createGuid()
        }
      })
      viewer.flyTo(entity)
    } else if (layerType === 5 || (layerType === 6 && changeType === 'b3dm')) {
      var tileset = viewer.scene.primitives.add(new PGEarth3DTileset({
        url : layerIp + serviceUrl,
        maximumScreenSpaceError: 2
      }));
      viewer.zoomTo(tileset);
    } else if (layerType === 8 || (layerType === 6 && changeType === 'lob') || (layerType === 6 && changeType === 'pld')) {
      var layer = new PldMeshLayer({
        url: layerIp + serviceUrl,
        viewer: viewer
      })
      viewer.scene.pageLODLayers.add(layer);
      layer.readyPromise.then(function(lodMesh) {
        viewer.camera.flyTo({
          destination: Cartesian3.fromDegrees(lodMesh.origin.x, lodMesh.origin.y, lodMesh.origin.z + 1500),
          duration: 1
        });
      })
    } else if (layerType === 25){
      let layer = createTileMapServiceImageryProvider({
        url: layerIp + serviceUrl,
        fileExtension: 'png'
      })
      viewer.imageryLayers.addImageryProvider(layer)
    }

    window.showMapShape = function (e, index){
      allPrimitiveLayers.map(val=>{
        viewer.scene.groundPrimitives.remove(val)
      })
      allFeatureLayer = []
      viewer.entities.removeById('point')
      lastIndex > -1 && $('#data'+lastIndex).removeClass('tr-active')
      if (lastIndex !== index) {
        $('#data'+index).addClass('tr-active')
      } else {
        lastIndex = ''
        return
      }

      let xhr = new XMLHttpRequest()
      xhr.onload = function (e) {
        if (this.status === 200 || this.status === 304) {
          let resData = this.response
          let datas = resData && resData.substring(resData.indexOf('('),resData.lastIndexOf(')')+1).replace(/\s+/g,",").replace(/\(/g,"[").replace(/\)/g,"]").replace(/,,/g,",")
          let type = resData.substring(0, resData.indexOf('(')-1)
          datas = JSON.parse(datas)
          if (type === 'POINT') {
            drawPoint(datas)
          } else {
            traverse(datas)
          }
        }
      }
      lastIndex = index
      xhr.open('get', '../../../service/gis/getLayerTable/'+index+'/?name='+layerName, true)
      xhr.send();

    }

    //选择每页显示多少条
    $('.table-footer').find('select[name="page_num"]').change(function () {
      $(".table-footer>span").remove();
      reLoadPage ()
    });

    /**
     * 循环遍历坐标数据
     * @param arr
     */
    function traverse(arr) {
      for (let a in arr) {

        if (arr[a] instanceof Array && arr[a][0] instanceof Array) {
          traverse(arr[a]); //递归遍历
        } else {
          drawShape(arr[a])
        }
      }
    }

    /**
     * 绘制图形
     * @param arr
     */
    function drawShape(arr){
      loading.start()
      let allArr = []
      if(originProj4js.crs_type === '2'){
        for(let i=0; i < arr.length - 1; i += 2){
          let mid = proj4(originProj4js.proj4js, '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs',[arr[i], arr[i+1]]) // 源坐标系，目标坐标系，需要转换的值
          allArr.push(mid[0], mid[1])
        }
      }else{
        allArr = arr
      }
      let instance = new GeometryInstance({
        geometry : new GroundPolylineGeometry({
          positions : Cartesian3.fromDegreesArray(allArr),
          width : 3.0
        }),
        attributes : {
          color : ColorGeometryInstanceAttribute.fromColor(Color.AQUA)
        },
        id: 'polyline'
      });

      let polylinePrimitive = viewer.scene.groundPrimitives.add(new GroundPolylinePrimitive({
        geometryInstances : instance,
        appearance : new PolylineMaterialAppearance({
          translucent : false,
          material: new Material({
            fabric : {
              type : 'Color',
              uniforms : {
                color : Color.AQUA
              }
            }
          })
        })
      }));
      allPrimitiveLayers.push(polylinePrimitive)
      polylinePrimitive.readyPromise.then(function () {
        loading.finish()
      })
    }
    /**
     * 绘制点
     * @param data
     */
    function drawPoint (data) {
      if(originProj4js.crs_type === '2'){
        data = proj4(originProj4js.proj4js, '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs',[data[0], data[1]]) // 源坐标系，目标坐标系，需要转换的值
      }
      //点要素样式
      viewer.entities.add({
        id: 'point',
        position : Cartesian3.fromDegrees(data[0], data[1]),
        point : {
          pixelSize : 10,
          color : Color.AQUA
        }
      })
    }

  });

  /**
   * 请求数据列表
   */
  function getTableDataList () {
    let xhr = new XMLHttpRequest()
    xhr.onload = function (e) {
      if(this.status === 200||this.status === 304){
        let result = JSON.parse(this.response)
        tableDatas = result.data // 获取表格数据
        $('#loadEffect').remove()
        if(!tableDatas){
          $('#dataTable tbody').html('<span class="no-data">没有可用数据</span>')
          return
        }
        columnsData = (baseData && baseData.attributes) && baseData.attributes.attribute
        $('#dataSize').html(tableDatas.length)
        loadTableData(1)
        reLoadPage()
      }
    }
    $('#loadEffect').show()
    xhr.open('post', '../../../service/gis/getLayerTable/?name='+layerName, true)
    xhr.send();
  }

  /**
   * 加载table数据
   **/
  function loadTableData(page){
    let rows = $('.table-footer').find('select[name="page_num"] option:selected').val()
    let tBody = $('#dataTable tbody')
    tBody.html('')
    for(let i=(page-1)*rows; i< rows*page; i++){
      let val = tableDatas[i]
      if (!val) {
        break
      }
      let str = `<tr onclick="showMapShape(-1, `+i+`)" id="data`+i+`">`
      columnsData.map(col=>{
        str += `<td>${!val[col.name]?'':val[col.name]}</td>`
      })
      str += `</tr>`
      tBody.append(str);
    }
  }

  /**
   * 加载分页插件
   */
  function reLoadPage () {
    $('.table-footer').prepend("<span></span>");
    var currentRows = $('.table-footer').find('select[name="page_num"] option:selected').val()
    $('.table-footer').children("span").createPage({
      pageCount: Math.ceil(tableDatas.length/currentRows), //总页数
      current: 1,    //初始页数
      backFn: function (p) {    //p为当前页数，点击有效
        page = p
        loadTableData(p)
      }
    });
  }

  function showDatas(e){
    let dataObj = document.getElementById('data')
    if(tableDatas.length === 0){
      getTableDataList()
    }
    if(e.className.indexOf('active')>0){
      e.setAttribute('class','all-btn data-btn')
      dataObj.style.display = 'none'
    }else{
      e.setAttribute('class','all-btn data-btn active')
      dataObj.style.display = 'block'
    }
  }

  function showFilter(e){
    let dataObj = document.getElementById('filterPanel')
    if(e.className.indexOf('active')>0){
      e.setAttribute('class','all-btn filter-btn')
      dataObj.className = 'filter-panel backmove'
      setTimeout(()=>{
        dataObj.style.right = '-400px'
      },5000)
    }else{
      e.setAttribute('class','all-btn filter-btn active')
      dataObj.style.display = ''
      dataObj.className = 'filter-panel move'
      setTimeout(()=>{
        dataObj.style.right = '166px'
      },5000)
    }
  }

  //墨卡托转经度
  function handle_me_x(x) {
    return x/20037508.34*180;
  }

  //墨卡托转纬度
  function handle_me_y(my) {
    var mmy = my / 20037508.34 * 180;
    y = 180 / Math.PI * (2 * Math.atan(Math.exp(mmy * Math.PI / 180)) - Math.PI / 2);
    return y;
  }
</script>
</body>
</html>
